package com.nexus.all.listener.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.nexus.all.dto.excel.UserExcelData;
import com.nexus.all.service.UserService;
import com.nexus.bean.utils.CollectionsUtil;
import com.nexus.bean.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class UserCheckListener extends AnalysisEventListener<UserExcelData> {

    private List<UserExcelData> excelDataList = new ArrayList<>();
    private static final int BATCH_COUNT = 1000;

    private List<String> errorList = new ArrayList<>();//校验错误信息

    private UserService userService;
    private Long userId;

    public UserCheckListener(UserService userService, Long userId) {
        this.userService = userService;
        this.userId = userId;
    }

    @Override
    public void invoke(UserExcelData data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        data.setRowIndex(context.readRowHolder().getRowIndex() + 1);
        excelDataList.add(data);
        if (excelDataList.size() >= BATCH_COUNT) {
            checkData();
            // 存储完成清理 list
            excelDataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //最后调用一次是因为如果invoke中添加完excel最后一条后没有达到批量编辑的数字，则最后直接调用方法进行编辑
        if (CollectionsUtil.isNotEmpty(excelDataList)) {
            checkData();
        }
        log.info("所有数据解析完成！");
    }


    private void checkData() {
        for (UserExcelData data : excelDataList) {
            if (StringUtils.isBlank(data.getUsername())) {
                errorList.add("第" + data.getRowIndex() + "行: 用户名为空");
            }
            if (StringUtils.isBlank(data.getPassword())) {
                errorList.add("第" + data.getRowIndex() + "行: 密码为空");
            }
        }
        userService.checkImportData(excelDataList, this, userId);
    }

    public List<String> getErrorList() {
        return errorList;
    }

}
